package com.webvihar.common.builders;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.webvihar.common.utils.Logger;

/**
 * @author Viswanath Kumar Sandu
 *
 */
public class JsonBuilder implements IJsonBuilder {

    private SerializerDeserializerInclusionStrategy serializerStrategy;
    private SerializerDeserializerInclusionStrategy deserializerStrategy;

    public JsonBuilder() {
        super();
    }
    
    public JsonBuilder(SerializerDeserializerInclusionStrategy s, SerializerDeserializerInclusionStrategy d) {
        super();
        serializerStrategy = s;
        deserializerStrategy = d;
    }
    
	public <T> T getEntityForJson(String json, Class<T> entity) {
		try {
		    if(deserializerStrategy != null) {
		        return new GsonBuilder().addDeserializationExclusionStrategy(deserializerStrategy).create().fromJson(json, entity);
		    } else {
		        return new Gson().fromJson(json, entity);
		    }
			
		}
		catch (Exception e) {
			Logger.logError(Logger.LOG_TAG, String.format("%s  ", this.getClass().getName()), e);
		}
		return null;
	}

	public <T> String getJsonForEntity(IJsonEntity<T> entity) {
		try {
		    if(serializerStrategy != null) {
		        return new GsonBuilder().serializeNulls().addSerializationExclusionStrategy(serializerStrategy).create().toJson(entity);
		    } else {
		        return new Gson().toJson(entity);
		    }
		}
		catch (Exception e) {
			Logger.logError(Logger.LOG_TAG, String.format("%s  ", this.getClass().getName()), e);
		}
		return null;
	}
}
